package com.call.service;

import com.call.Constants;
import com.call.data.DataBaseHelper;
import com.call.data.MissSMS;
import com.call.data.MissSMSData;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SMSListener extends BroadcastReceiver{

	private final String TAG = "SMSListener";
	private ISMSService bindService = null;
	
	public SMSListener(ISMSService bindService) {
		super();
		Log.v(TAG, "SMSListener Constructer");
		this.bindService = bindService;
	}
	
	//public void setBindService(ISMSService bindService)
	//{
	//	this.bindService = bindService;
	//}
	
	public SMSListener() {
		super();
		//this.bindService = bindService;
		Log.v(TAG, "Constructer SMSListener");
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.v(TAG, "onReceive");
		
		if (!MissCallAndPhoneNumberService.isInstanceCreated()) return;
		
		Bundle bundle = intent.getExtras();

		Object messages[] = (Object[]) bundle.get("pdus");
		SmsMessage smsMessage[] = new SmsMessage[messages.length];
		for (int n = 0; n <  messages.length; n++) {
			smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
		}

		// show first message
		Toast toast = Toast.makeText(context,
		"Auto SMS: " + smsMessage[0].getDisplayMessageBody() + " sdt : " + smsMessage[0].getOriginatingAddress() , Toast.LENGTH_LONG);
		toast.show();
		
		long now = System.currentTimeMillis();
		String time = String.valueOf(now);
		String phoneNumber = smsMessage[0].getOriginatingAddress();
		String messageBody = smsMessage[0].getDisplayMessageBody();
		
		if (SMSService.isInstanceCreated()) {
			Log.v(TAG, "onReceive -> bindService.AddSMSReceiverInfo ");
			//if ()
			
//			MissSMSData m_objSMSData  = MissSMSData.GetMissSMSData(context, Constants.MISSSMS_TABLENAME);
//			
//			ContentValues values = new ContentValues();
//			
//			values.put(MissSMSData.TableColumns.SMSTime, now);
//			values.put(MissSMSData.TableColumns.SMSNumber, phoneNumber);
//			values.put(MissSMSData.TableColumns.SMSMessageBody, messageBody);
//
//			m_objSMSData.insert(values);
			
			DataBaseHelper dbHelper = new  DataBaseHelper(context);
			
			
			MissSMS sms = new MissSMS(time, phoneNumber, messageBody);
			
			dbHelper.AddSMS(sms);
			
			dbHelper.getSMSCount();
			
			//m_objSMSData
			
			//bindService = SMSService.instance.serviceBind;
			//if (bindService != null)
			//	bindService.AddSMSReceiverInfo(phoneNumber, now, messageBody);
			//else
			//	Log.v(TAG, "onReceive -> bindService == null ");
		}
		
	}

}
